; (function ($) {
  const Affix = function (ele, opt) {
    this.$element = $(ele)
    this.options = $.extend({}, Affix.DEFAULTS, opt)
    this.$target = $(this.options.target)
    this.elementPosition = this.$element.offset().top

    this.checkPosition()
    this.$target.on('scroll', $.proxy(this.checkPosition, this))
  }
  Affix.DEFAULTS = {
    offset: 0,
    target: window
  }

  Affix.prototype.checkPosition = function () {
    let scrollTop = this.$target.scrollTop()
    let position = this.$element.offset()
    
    // console.log(`elementPosition: ${this.elementPosition} , position: ${position.top} , scrollTop: ${scrollTop}`)
    this.elementPosition <= scrollTop ?
      position.top <= scrollTop ? this.$element.addClass('affix') : false
      : this.$element.removeClass('affix')
  }
  
  $.fn.affix = function(options){
    let affix = new Affix(this, options)
  }

  $(window).on('load', function () {
    $('[data-plugin="affix"]').each(function(){
      $(this).affix()
    })
  })
})(jQuery)